package com.shop.controller;

import com.alibaba.fastjson.JSONObject;
import com.shop.constant.Constants;

import com.shop.entity.LookCartVO;
import com.shop.entity.User;
import com.shop.exception.*;
import com.shop.factory.ObjectFactory;
import com.shop.service.UserService;

import com.shop.service.impl.UserServiceImpl;
import com.shop.util.GetMap;
import com.shop.util.MD5Util;
import com.shop.util.PrintJson;
import com.shop.util.ReturnImg;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: ${file_name}</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2020</p>
 * <p>Company: www.baidudu.com</p>

 * 410 系统正在维护中
 * 411 用户不存在
 * 412 用户已存在
 * 413 用户信息修改失败
 * 414 用户头像修改失败
 * 415 用户密码修改失败

 * @author andy
 * @version 1.0
 * @date ${date}
 */
@WebServlet("/user/*")
public class UserController extends HttpServlet {

    private UserService service = (UserServiceImpl) ObjectFactory.getInstance(Constants.USER_SERVICE_KEY);



    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        if("/shop/user/login".equals(uri)) {
            login(req,resp);
        }else if("/shop/user/register".equals(uri)) {
            register(req,resp);
        }else if("/shop/user/user_information".equals(uri)) {
            getUserInformation(req,resp);
        }else if("/shop/user/user_information/change".equals(uri)) {
            changeUserInformation(req,resp);
        }else if("/shop/user/upload".equals(uri)) {
            changeImg(req,resp);
        }else if("/shop/user/head_img".equals(uri)) {
            getHeadImg(req,resp);
        }else if("/shop/user/change_pwd".equals(uri)) {
            changePwd(req,resp);
        }
    }

    private void changePwd(HttpServletRequest req, HttpServletResponse resp) {
        //解析
        JSONObject json = PrintJson.paraseJson(req);
        String old_pwd = json.getString("old_pwd");
        old_pwd = MD5Util.getMD5(old_pwd);
        String new_pwd = json.getString("new_pwd");
        new_pwd = MD5Util.getMD5(new_pwd);
        String a_new_pwd = json.getString("a_new_pwd");
        String u_id = req.getParameter("u_id");

        Map<String,Object> map = null;
        try {
            service.changePwd(old_pwd,new_pwd,a_new_pwd,u_id);
            map = GetMap.getMap(200,"密码修改成功");
        } catch (changePwdException e) {
            map = GetMap.getMap(415,e.getMessage());
            e.printStackTrace();
        } catch (DAOException e) {
            map = GetMap.getMap(410,e.getMessage());
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }

    private void getHeadImg(HttpServletRequest req, HttpServletResponse resp) {
        String u_id = req.getParameter("u_id");

        Map<String,Object> map = null;
        try {
            User user = service.selectUserInformationById(Integer.parseInt(u_id));
            ReturnImg.returnImg(resp,user.getU_img());
            map = GetMap.getMap(200,"返回头像成功");
        } catch (UserNotExistException e) {
            map = GetMap.getMap(411,"返回头像失败");
            e.printStackTrace();
        } catch (DAOException e) {
            map = GetMap.getMap(410,"返回头像失败");
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }

    //修改用户头像
    private void changeImg(HttpServletRequest request, HttpServletResponse resp) {
        String id = request.getParameter("u_id");
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //获得磁盘文件条目工厂。
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //获取文件上传需要保存的路径，upload文件夹需存在。
        //request.getSession().getServletContext().getRealPath("/upload");
        String path = "d:/img/image/user/";
        //设置暂时存放文件的存储室，这个存储室可以和最终存储文件的文件夹不同。因为当文件很大的话会占用过多内存所以设置存储室。
        factory.setRepository(new File(path));
        //设置缓存的大小，当上传文件的容量超过缓存时，就放到暂时存储室。
        factory.setSizeThreshold(1024*1024);
        //上传处理工具类（高水平API上传处理？）
        ServletFileUpload upload = new ServletFileUpload(factory);

        Map<String,Object> map = null;
        try{
            //调用 parseRequest（request）方法  获得上传文件 FileItem 的集合list 可实现多文件上传。
            List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
            for(FileItem item:list){
                //如果传入的是非简单字符串，而是图片，音频，视频等二进制文件。
                //获取路径名
                String value = item.getName();
                //修改上传图片名。
                String filename = id + value.substring(value.lastIndexOf("."));
                /*第三方提供的方法直接写到文件中。*/
                item.write(new File(path,filename));
                String url = "d:/img/image/user/"+filename;
//                returnJepgImg(resp,url);
                //更新数据库中用户的头像
                service.changeUserHeadImg(id,url);
                map = GetMap.getMap(200,"头像修改成功");
            }
        }catch(Exception e){
            map = GetMap.getMap(414,"用户头像修改失败");
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }

    //改变用户信息
    private void changeUserInformation(HttpServletRequest req, HttpServletResponse resp) {
        //解析
        JSONObject json = PrintJson.paraseJson(req);

        String id = req.getParameter("u_id");
        int u_id = Integer.parseInt(id);
        String username = json.getString("username");
        String age = json.getString("age");
        int u_age = Integer.parseInt(age);
        String sex = json.getString("sex");
        String location = json.getString("location");
        String introduction = json.getString("introduction");
//
//        String id = req.getParameter("u_id");
//        int u_id = Integer.parseInt(id);
//        String username = req.getParameter("username");
//        String age = req.getParameter("age");
//        int u_age = Integer.parseInt(age);
//        String sex = req.getParameter("sex");
//        String location = req.getParameter("location");
//        String introduction = json.getString("introduction");
        User user = new User(username,u_age,sex,location,introduction);

        Map<String, Object> map = null;
        try {
            //获取用户信息
            service.updateUserInformation(user,u_id);
            map = GetMap.getMap(200, "用户信息修改成功");
            //map.put("data",user);
        } catch (DAOException e) {
            map = GetMap.getMap(410, e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (UserInformationChangeException e) {
            map = GetMap.getMap(413, e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);

    }

    //个人中心界面
    private void getUserInformation(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("user_id");
        int user_id = Integer.parseInt(id);

        Map<String, Object> map = null;
        try {
            //获取用户信息
            User user = service.selectUserInformationById(user_id);
            map = GetMap.getMap(200, "用户信息获取成功");
            map.put("data",user);
        } catch (DAOException e) {
            map = GetMap.getMap(410, e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (UserNotExistException e) {
            map = GetMap.getMap(411, e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }

    //注册
    private void register(HttpServletRequest req, HttpServletResponse resp) {
        JSONObject json = PrintJson.paraseJson(req);
        String username = json.getString("username");
        String password = json.getString("password");
        //md5加密
        password = MD5Util.getMD5(password);
        String age = json.getString("age");
        int u_age = Integer.parseInt(age);
        String sex = json.getString("sex");
        String location = json.getString("location");
        String introduction = json.getString("introduction");
        User user = new User(0,username,password,0,u_age,sex,location,"d:/img/image/user/default.png",introduction);


        Map<String, Object> map = null;
        try {
            String img_name = service.register(user);
            map = GetMap.getMap(200, "注册成功");
        } catch (DAOException e) {
            map = GetMap.getMap(410, e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (UserExistException e) {
            map = GetMap.getMap(412, e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (UserNotExistException e) {
            map = GetMap.getMap(411, e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        PrintJson.printJsonObj(resp,map);
    }

    //登录
    private void login(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        //解析
        JSONObject json = PrintJson.paraseJson(req);
        String username = json.getString("username");
        String password1 = json.getString("password");
//        String username = req.getParameter("username");
//        String password = req.getParameter("password");
        //md5加密
        String password = MD5Util.getMD5(password1);

        Map<String, Object> map = null;
        try{
            User user = service.login(username, password);
            user.setU_pwd(password1);
            map = GetMap.getMap(200, "登录成功");
            map.put("data",user);
        }catch(DAOException e){
            map = GetMap.getMap(410, e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (UserNotExistException e) {
            map = GetMap.getMap(411, e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
    }


}
